package com.alvin.demo.controller;

import com.alvin.demo.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@Slf4j
public class LoginController {

    // 登录接口
    @PostMapping("/login")
    public R login(@RequestBody Map<String , String> userMap) {
        if (ObjectUtils.isEmpty(userMap.get("username")) || ObjectUtils.isEmpty(userMap.get("password"))) {
            return R.error("请输入用户名和密码！");
        }
        //用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                userMap.get("username"),
                userMap.get("password")
        );
        try {
            //进行验证，这里可以捕获异常，然后返回对应信息
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException e) {
            log.error("用户名不存在！", e);
            return R.error("用户名不存在！");
        } catch (AuthenticationException e) {
            log.error("账号或密码错误！", e);
            return R.error("账号或密码错误！");
        } catch (AuthorizationException e) {
            log.error("没有权限！", e);
            return R.error("没有权限");
        }
        return R.ok("login success");
    }

    @RequiresRoles("admin") // 优先级 方法注解 > 配置方式
    @GetMapping("/admin")
    public R admin() {
        return R.ok("admin success!");
    }

    @RequiresPermissions("query")
    @GetMapping("/query")
    public R index() {
        return R.ok("query success!");
    }

    @RequiresPermissions("add")
    @GetMapping("/add")
    public R add() {
        return R.ok("add" , "add success!");
    }

    @GetMapping("/unauthorized")
    public R unauthorized(){
        return R.error("没有该操作的权限！");
    }
}
